import {
	createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized, Router, RouteRecordRaw
} from 'vue-router';
import { indexPath, loginPath, needPermissionPath } from '../config.ts';
import axios from '@/config/axios/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { config } from '@/config/directive/permission/config.ts';
import { usePermissionStore } from '@/config/pinia/permission.store.ts';
import { VxeUI } from '@/config/vxe/vxe-pc-ui/index.ts';
const staticRoutes: Array<RouteRecordRaw> = [
	{
		path     : '/',
		redirect : loginPath
	},
	{
		path      : loginPath,
		name      : 'Login',
		component : () => import('@/components/login.vue')
	},
	{
		path      : indexPath,
		name      : 'Index',
		component : () => import('@/components/index.vue')
	}
	/*{
	 path      : '/ui',
	 name      : 'Vxe-UI',
	 component : () => import('@/components/ui/index.vue')
	 }*/
];
const router: Router = createRouter({
	history : createWebHashHistory(/*import.meta.env.VUE_APP_BASE_URL*/),
	routes  : staticRoutes
});
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): void => {
	if ('1' === config.loadMode) {
		// 判断是否是需要权限的路径
		if (needPermissionPath.includes(to.fullPath)) {
			const permissionStore = usePermissionStore();
			axios<any, JsonResultProps<any>, any>({
				method : 'POST',
				url    : '/permission'
			}).then((jsonResult: JsonResultProps<any>): void => {
				if (jsonResult.status) {
					// 请求到数据后放入pinia存着
					permissionStore.setPermissionList(jsonResult.data);
					// 初始化完权限数据后放行
					next();
				} else {
					VxeUI.modal.message({
						content : jsonResult.msg,
						status  : 'warning',
						id      : 'routeProtectWarn'
					});
					return;
				}
			}).catch((error: any) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'routeProtectError'
				});
			});
		} else {
			// 不需要权限的页面直接放行
			next();
		}
	} else {
		// 不需要权限直接放行
		next();
	}
});
export default router;